import {harTasks,OhosHarContext,OhosPluginId,Target} from '@ohos/hvigor-ohos-plugin';
import { hvigor, HvigorNode, HvigorPlugin} from '@ohos/hvigor';
import * as fs from 'fs';

export default {
    system: harTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
    plugins:[renameHarTask()]         /* Custom plugin to extend the functionality of Hvigor. */
}

/**
 * 重命名Har任务
 *
 * @returns
 */
function renameHarTask() {
    return {
        pluginId: 'RenameHarTaskID',
        apply(pluginContext) {
            pluginContext.registerTask({
                // 编写自定义任务
                name: 'renameHarTask',
                run: (taskContext) => {
                    // 读取oh-package.json5，解析出version
                    const packageFile = taskContext.modulePath + '\\oh-package.json5';
                    console.log('file: ', packageFile);
                    let fileContent = fs.readFileSync(packageFile, 'utf8');
                    fileContent = fileContent.replace(/\/\/.*$/gm, '').replace(/\/\*[\s\S]*?\*\//g, '');
                    console.log(fileContent);
                    const content: OhPackage = JSON.parse(fileContent);
                    const version = content.version;
                    const author = content.author;

                    console.log('renameHarTask: ', taskContext.moduleName, taskContext.modulePath,);
                    const sourceFile =
                        taskContext.modulePath + '\\build\\default\\outputs\\default\\' + taskContext.moduleName + '.har';
                    const targetPath = taskContext.modulePath + '\\build\\default\\outputs\\target\\';
                    const pattern = /^@([a-zA-Z0-9_-]+)\//g;
                    const harName = content.name.replace(pattern, '')
                    const targetFile = targetPath + harName + '-' + version + '.har';
                    console.log('renameHarTask: sourceFile: ', sourceFile);
                    console.log('renameHarTask: targetFile: ', targetFile);

                    // 创建目录
                    fs.mkdir(targetPath, { recursive: true }, (err) => {
                        if (err) {
                            throw err;
                        }
                        // 移动并修改产物文件名
                        fs.rename(sourceFile, targetFile, (err) => {
                            console.log('err: ' + err);
                        });
                    });
                },
                // 确认自定义任务插入位置
                dependencies: ['default@PackageHar'],
                postDependencies: ['assembleHar']
            })
        }
    }
}

interface OhPackage {
    name: string;
    version: number;
    description: string;
    author: string;
}